from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.throttling import UserRateThrottle, ScopedRateThrottle

from .models import BookInfo
from .serializer import BookSerializer
from rest_framework.views import APIView

# Create your views here.


class BooksView(APIView):
    """获取所有图书、保存图书"""

    # 只针对个别视图的认证和权限
    authentication_classes = (BasicAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)
    throttle_classes = UserRateThrottle

    def get(self, req):
        """获取所有图书"""
        # 查询所有的图书信息
        throttle_scope = 'get_books'
        print(req.query_params)
        books = BookInfo.objects.all()

        ser = BookSerializer(books, many=True)

        return Response(ser.data)  # data 是Serializer里提供的方法

    def post(self, req):
        """保存图书"""
        # 获取前端数据
        # json_dict = json.loads(req.body.decode())
        data = req.data
        # 2、校验数据
        ser = BookSerializer(data=data)
        ser.is_valid()
        # print(ser.validated_data)  # 获取验证后的字段

        # 保存数据
        ser.save()

        # 4、返回结果
        # return JsonResponse(ser.errors)
        return Response(ser.data)


class BookView(APIView):
    """获取单一图书、更新图书、删除图书"""

    def get(self, req, book_id):
        """获取单一图书"""
        book = BookInfo.objects.get(id=book_id)

        ser = BookSerializer(book)  # 只验证一个，不需要写many

        return JsonResponse(ser.data)  # 不是返回列表，不用写safe

    def put(self, req, book_id):
        """更新图书"""
        # 接收数据
        # json_dict = json.loads(req.body.decode())
        data = req.data
        # 校验数据
        try:
            book = BookInfo.objects.get(id=book_id)
        except:
            return JsonResponse({'error': '信息错误'}, status=400)
        ser = BookSerializer(book, data=data)
        ser.is_valid()  # 验证要记得

        # 3、更新数据
        ser.save()

        # 4、返回结果
        return Response(ser.data)

    def delete(self, req, book_id):
        """删除图书"""
        # 获取要删除的图书对象
        try:
            book = BookInfo.objects.get(id=book_id)
        except:
            return JsonResponse({'error': '信息错误'}, status=400)

        book.is_is_delete = True
        book.save()
        return JsonResponse({})  # 删除成功，返回空即可

